package cn.edu.tsinghua.thss.alg.closestpair.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import cn.edu.tsinghua.thss.alg.closestpair.algorithm.ClosestPair;
import cn.edu.tsinghua.thss.alg.closestpair.algorithm.Rand;
import cn.edu.tsinghua.thss.alg.closestpair.model.PairResult;

public class ClosestPairFrame extends JFrame implements ActionListener {

	private static final long serialVersionUID = -3919476726078713428L;

	private static ClosestPairFrame frame = new ClosestPairFrame();

	private PointsPanel pointsPanel;
	private StatusBar statusBar;
	private JLabel timeLabel;
	private JTextField input;
	PairResult result;

	public JLabel getTimeLabel() {
		return timeLabel;
	}

	public StatusBar getStatusBar() {
		return statusBar;
	}

	private ClosestPairFrame() {
		pointsPanel = new PointsPanel(this);
		this.setTitle("Closest Pair");
		this.setSize(new Dimension(600, 800));
		this.setLayout(new BorderLayout());
		this.add(pointsPanel, BorderLayout.CENTER);

		JPanel rightPanel = new JPanel();
		rightPanel.setSize(100, 500);
		rightPanel.setLayout(new GridLayout(20, 1));
		JButton button = new JButton("Finish");
		button.setSize(100, 20);
		rightPanel.add(button);
		timeLabel = new JLabel("Time:");
		timeLabel.setSize(100, 20);
		rightPanel.add(timeLabel);

		JLabel randLabel = new JLabel("Random:");
		input = new JTextField("");
		rightPanel.add(randLabel);
		rightPanel.add(input);
		JButton button2 = new JButton("Compute");
		rightPanel.add(button2);
		this.getContentPane().add(rightPanel, BorderLayout.EAST);

		statusBar = new StatusBar();
		this.getContentPane().add(statusBar, BorderLayout.SOUTH);

		button.addActionListener(this);
		button2.addActionListener(this);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}

	public static ClosestPairFrame getInstance() {
		return frame;
	}

	public double doComputing(double[][] points, int size) {
		double start = System.currentTimeMillis();
		this.result = ClosestPair.findClosestPair(points, size);
		return System.currentTimeMillis() - start;
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equals("Finish")) {
			double[][] points = pointsPanel.getPoints();
			double time = doComputing(points, points.length);
			pointsPanel.drawLine(result.getX1(), result.getY1(),
					result.getX2(), result.getY2());
			timeLabel.setText(time + "ms");
		} else if (e.getActionCommand().equals("Compute")) {
			int size = Integer.parseInt(input.getText());
			double[][] points = Rand.getRandomPoints(size);
			double time = doComputing(points, size);
			timeLabel.setText(time + "ms");
		}
	}
}
